package com.iteaj.iot.test.mqtt;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.iteaj.iot.client.mqtt.message.MqttClientMessage;
import com.iteaj.iot.message.DefaultMessageHead;
import com.iteaj.iot.test.TestProtocolType;
import com.iteaj.iot.test.TestStatus;
import com.iteaj.iot.test.TestStatusHeader;
import com.iteaj.iot.utils.ByteUtil;
import io.netty.handler.codec.mqtt.MqttPublishMessage;
import io.netty.handler.codec.mqtt.MqttQoS;
import org.aspectj.weaver.ast.Test;

public class MqttClientTestMessage extends MqttClientMessage {

    /**
     * 此构造函数必须存在
     * @param message
     */
    public MqttClientTestMessage(MqttPublishMessage message) {
        super(message);
    }

    public MqttClientTestMessage(MessageHead head, String topic) {
        super(head, topic);
    }

    public MqttClientTestMessage(MessageHead head, MqttQoS qos, String topic) {
        super(head, qos, topic);
    }

    public MqttClientTestMessage(MessageHead head, MessageBody body, String topic) {
        super(head, body, topic);
    }

    @Override
    protected MessageHead doBuild(byte[] payload) {
        JSONObject jsonObject = JSONUtil.parseObj(ByteUtil.bytesToString(payload));
        TestProtocolType type = jsonObject.get("type", TestProtocolType.class);
        if(type == TestProtocolType.PIReq) {
            return new TestStatusHeader(jsonObject.getStr("equipCode"),
                    jsonObject.getStr("messageId"), type, jsonObject.get("status", TestStatus.class));
        } else if(type == TestProtocolType.WillTop) {
            return new TestStatusHeader(jsonObject.getStr("equipCode"),
                    jsonObject.getStr("messageId"), type, jsonObject.get("status", TestStatus.class));
        } else {
            return new DefaultMessageHead(jsonObject.getStr("equipCode"), jsonObject.getStr("messageId"), type);
        }
    }

}
